package com.nnnu.wsnackshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nnnu.wsnackshop.mapper.MemberGrowthMapper;
import com.nnnu.wsnackshop.mapper.MemberPointsMapper;
import com.nnnu.wsnackshop.mapper.MembersMapper;
import com.nnnu.wsnackshop.mapper.OrdersMapper;
import com.nnnu.wsnackshop.pojo.entity.MemberGrowth;
import com.nnnu.wsnackshop.pojo.entity.MemberPoints;
import com.nnnu.wsnackshop.pojo.entity.Members;
import com.nnnu.wsnackshop.pojo.entity.Orders;
import com.nnnu.wsnackshop.service.IMembersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 会员信息表 服务实现类
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MembersServiceImpl extends ServiceImpl<MembersMapper, Members> implements IMembersService {

    private final MemberPointsMapper memberPointsMapper;
    private final MemberGrowthMapper memberGrowthMapper;
    private final OrdersMapper ordersMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMemberPoints(Integer userId, Integer points, Integer changeType, String description) {
        log.info("更新会员积分: userId={}, points={}, changeType={}, description={}", userId, points, changeType,
                description);

        // 查询会员信息
        Members member = getMemberByUserId(userId);
        if (member == null) {
            return false;
        }

        // 创建积分记录
        MemberPoints memberPoints = new MemberPoints();
        memberPoints.setMemberId(member.getId());
        memberPoints.setChangeType(changeType);
        memberPoints.setPoints(points);
        memberPoints.setDescription(description);
        memberPoints.setCreatedAt(LocalDateTime.now());

        // 保存积分记录
        int insertResult = memberPointsMapper.insert(memberPoints);
        if (insertResult <= 0) {
            log.error("保存积分记录失败: userId={}, points={}", userId, points);
            return false;
        }

        // 更新会员积分
        int currentPoints = member.getPoints() != null ? member.getPoints() : 0;
        if (changeType == 1) {
            // 增加积分
            member.setPoints(currentPoints + points);
        } else if (changeType == 2) {
            // 减少积分
            int newPoints = currentPoints - points;
            member.setPoints(Math.max(newPoints, 0)); // 确保积分不为负数
        }

        // 更新会员信息
        member.setUpdatedAt(LocalDateTime.now());
        int updateResult = baseMapper.updateById(member);

        if (updateResult <= 0) {
            log.error("更新会员积分失败: userId={}, points={}", userId, points);
            return false;
        }

        log.info("更新会员积分成功: userId={}, newPoints={}", userId, member.getPoints());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMemberGrowth(Integer userId, Integer growthValue, Integer changeType, String description) {
        log.info("更新会员成长值: userId={}, growthValue={}, changeType={}, description={}", userId, growthValue, changeType,
                description);

        // 查询会员信息
        Members member = getMemberByUserId(userId);
        if (member == null) {
            log.error("会员不存在: userId={}", userId);
            return false;
        }

        // 创建成长值记录
        MemberGrowth memberGrowth = new MemberGrowth();
        memberGrowth.setMemberId(member.getId());
        memberGrowth.setChangeType(changeType);
        memberGrowth.setGrowthValue(growthValue);
        memberGrowth.setDescription(description);
        memberGrowth.setCreatedAt(LocalDateTime.now());

        // 保存成长值记录
        int insertResult = memberGrowthMapper.insert(memberGrowth);
        if (insertResult <= 0) {
            log.error("保存成长值记录失败: userId={}, growthValue={}", userId, growthValue);
            return false;
        }

        // 更新会员成长值
        int currentGrowth = member.getGrowthValue() != null ? member.getGrowthValue() : 0;
        if (changeType == 1) {
            // 增加成长值
            member.setGrowthValue(currentGrowth + growthValue);
        } else if (changeType == 2) {
            // 减少成长值
            int newGrowth = currentGrowth - growthValue;
            member.setGrowthValue(Math.max(newGrowth, 0)); // 确保成长值不为负数
        }

        // 检查是否需要升级会员等级
        checkAndUpdateMemberLevel(member);

        // 更新会员信息
        member.setUpdatedAt(LocalDateTime.now());
        int updateResult = baseMapper.updateById(member);

        if (updateResult <= 0) {
            log.error("更新会员成长值失败: userId={}, growthValue={}", userId, growthValue);
            return false;
        }

        log.info("更新会员成长值成功: userId={}, newGrowthValue={}", userId, member.getGrowthValue());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMemberByOrderComplete(Integer userId, Long orderId, BigDecimal orderAmount) {
        log.info("根据订单完成更新会员积分和成长值: userId={}, orderId={}, orderAmount={}", userId, orderId, orderAmount);

        // 查询订单信息（确保订单存在且已完成）
        Orders order = ordersMapper.selectById(orderId);
        if (order == null) {
            log.error("订单不存在: orderId={}", orderId);
            return false;
        }

        if (order.getOrderStatus() != 4) {
            log.error("订单未完成，无法更新积分和成长值: orderId={}, orderStatus={}", orderId, order.getOrderStatus());
            return false;
        }

        // 计算积分（1元= 1 积分，向下取整）
        int points = orderAmount.intValue();

        // 计算成长值（1元=1成长值，向下取整）
        int growthValue = orderAmount.intValue();

        // 更新积分
        boolean pointsUpdated = updateMemberPoints(userId, points, 1,
                "完成订单 #" + order.getOrderNo() + " 奖励" + points + "积分");

        // 更新成长值
        boolean growthUpdated = updateMemberGrowth(userId, growthValue, 1,
                "完成订单 #" + order.getOrderNo() + " 奖励" + growthValue + "成长值");

        return pointsUpdated && growthUpdated;
    }

    /**
     * 根据用户ID获取会员信息
     */
    private Members getMemberByUserId(Integer userId) {
        LambdaQueryWrapper<Members> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Members::getUserId, userId);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 检查并更新会员等级
     * 根据成长值判断是否需要升级会员等级
     */
    private void checkAndUpdateMemberLevel(Members member) {
        // 0-99: 普通会员 (level 1)
        // 100-499: 银卡会员 (level 2)
        // 500-999: 金卡会员 (level 3)
        // 1000+: 钻石会员 (level 4)

        int growthValue = member.getGrowthValue() != null ? member.getGrowthValue() : 0;
        Integer currentLevelId = member.getMemberLevelId();

        if (growthValue >= 1000) {
            member.setMemberLevelId(4); // 钻石会员
        } else if (growthValue >= 500) {
            member.setMemberLevelId(3); // 金卡会员
        } else if (growthValue >= 100) {
            member.setMemberLevelId(2); // 银卡会员
        } else {
            member.setMemberLevelId(1); // 普通会员
        }

        // 如果等级有变化，记录日志
        if (currentLevelId == null || !currentLevelId.equals(member.getMemberLevelId())) {
            log.info("会员等级变更: memberId={}, oldLevel={}, newLevel={}",
                    member.getId(), currentLevelId, member.getMemberLevelId());
        }
    }
}
